package com.itheima.sh.controller;

import com.itheima.sh.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("consumer")
@CrossOrigin(origins = "*")
public class ConsumerController {
    //获得RestTemplate对象
    @Autowired
    private RestTemplate restTemplate;

    //拉取服务
    @Autowired
    private DiscoveryClient discoveryClient;
    @GetMapping("{username}")
    public User finduser(@PathVariable("username") String username) {
        List<ServiceInstance> instances = discoveryClient.getInstances("USER-SERVICE");
        ServiceInstance serviceInstance = instances.get(0);
        //获取主机地址
        String host = serviceInstance.getHost();
        //获取端口号
        int port = serviceInstance.getPort();
        //获取url
//        String url = serviceInstance.getUri().toString();
        String url= "http://user-service/user/"+username;
        //restTemplate调用远程请求
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }
}
